package com.dap.validation;

import com.dap.annotation.DapDateFormat;
import com.dap.commons.Constants;
import com.dap.exception.PlatformException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateValidation implements ConstraintValidator<DapDateFormat, Object> {
    private static Date minDate = null;
    private static Date maxDate = null;

    private static Logger logger = LoggerFactory.getLogger(DateValidation.class);

    static {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            minDate = sdf.parse("19000101");
            maxDate = sdf.parse("40001231");
        } catch (ParseException e) {
            logger.error("DateValidation init failure.");
            throw new PlatformException(Constants.ResponseCode.GENERAL_EXCEPTION, new String[]{"DateValidation init failure."}, e);
        }
    }

    @Override
    public void initialize(DapDateFormat constraintAnnotation) {
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        //Date为非必输项,如果需要判断null,使用@NotNull注解,此方法只验证Date非null的情况
        if (value == null)
            return true;

        if (value instanceof java.util.Date) {
            java.util.Date date = (java.util.Date) value;
            return (0 <= date.compareTo(minDate) && date.compareTo(maxDate) <= 0);
        } else {
            //非DATE类型,返回false
            return false;
        }
    }

}
